/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
package com.wealth.commodity.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.commodity.entity.Category;
import com.wealth.commodity.entity.Goods;
import com.wealth.commodity.entity.GoodsPic;
import com.wealth.commodity.entity.GoodsVirtual;
import com.wealth.commodity.enums.GoodsStatusEnum;
import com.wealth.commodity.service.ICategoryService;
import com.wealth.commodity.service.IGoodsService;
import com.wealth.merchant.entity.Activity;
import com.wealth.merchant.entity.Market;
import com.wealth.merchant.entity.Merchant;
import com.wealth.merchant.enums.MarketEnum;
import com.wealth.merchant.service.IActivityService;
import com.wealth.merchant.service.IMerchantService;
import com.wealth.platform.service.ISldConfigService;
import com.wealth.system.entity.User;
import com.wealth.system.service.ShiroUser;
import com.wealth.system.web.controller.BaseController;

import iaas.annotation.Log;
import iaas.enums.StatusEnum;
import iaas.utils.RedirectMessage;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping(value = "/manage/commodity/goods")
public class GoodsController extends BaseController {

	Logger logger = Logger.getLogger(GoodsController.class);

	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private ICategoryService categoryService;
	@Autowired
	private IActivityService activityService;
	@Autowired
	private IMerchantService merchantService;
	@Autowired 
	private ISldConfigService configService;
	@InitBinder
	public void initBinder(WebDataBinder binder){
		//注册自定义的属性编辑器，适合日期
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		CustomDateEditor dateEditor = new CustomDateEditor(df, true);
		// 表示如果命令对象有Date类型的属性，将使用该属性编辑器进行类型转换
		binder.registerCustomEditor(Date.class, dateEditor);
	}
	
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		try {
			if (id != -1) {
				Goods goods = goodsService.get(id);
				model.addAttribute("goods", goods);
			}
		} catch (Exception e) {
			logger.error("初始化错误", e);
		}
	}

	/**
	 * 列表
	 * @throws Exception 
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) throws Exception {
		try{
			// 查询商品分类和活动
			List<Category> categoryList = categoryService.findByStatusAndCorpId(StatusEnum.NORMAL.getValue(), 1L);
			model.addAttribute("categoryList", categoryList);
			
			// 查询所有商户
			List<Merchant> merchantList = merchantService.findByPropertyName("status", StatusEnum.NORMAL.getValue(), Merchant.class);
			model.addAttribute("merchantList", merchantList);
						
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			model.addAttribute("corpid", corpid);
			return "commodity/goods/list";
		} catch (Exception e) {
			logger.error("列表页面错误", e);
			return "system/500";
		}
	}
	
	
	
	/**
	 * 获取企业域名
	 * @throws Exception 
	 */
	@RequestMapping(value="createurl",method=RequestMethod.GET)
	public String tocreateurl(Model model){
		 try {
			model.addAttribute("sldList", configService.getSldConfidAndCorpIdNotNoe());
			return "commodity/goods/createUrl";
		} catch (Exception e) {
			return "system/500";
		}
	}
	/**
	 * 列表ajax查询数据
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getJson(Model model, JqGridRequest request) {
		try {

			User user = ShiroUser.getInstance().getUser();
			Page<Goods> page;
			if(user.getUsername().equals("admin")){
				//平台查询
				page = goodsService.get(1L, request, Goods.class);
			}else{
				//商户查询
				Merchant merchant = merchantService.getMerchantByUserId(user.getId());
				page = goodsService.getAllByMerchantId(merchant.getId(), request);
			}

			return JqGridUtil.getJqGrirdResponse(page);
		} catch (Exception e) {
			logger.error("列表错误！", e);
			return null;
		}
	}

	/**
	 * 详情
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String infoForm(Model model, @PathVariable("id") Long id) {
		try {
			Goods goods = goodsService.get(id);
			model.addAttribute("goods", goods);
			return "commodity/goods/info";
		} catch (Exception e) {
			logger.error("详情页面错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 创建页面
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String createForm(Model model) {
		try {
			// 根据商户管理账号  查询商户信息
			User user = ShiroUser.getInstance().getUser();
			Merchant merchant = merchantService.getMerchantByUserId(user.getId());
			
			model.addAttribute("merchant", merchant);
			
			//通过市场判断商品是否为虚拟商品
			if(merchant!=null){
			Market market = merchant.getMarket();
			model.addAttribute("market",market);
		 
			 
			// 查询商品分类和活动
			List<Category> categoryLists = categoryService.getCategoryByCorpIdAndMarketIdAndStatusAndParentIdIsNull(1L, market.getId(), StatusEnum.NORMAL.getValue());
			model.addAttribute("categoryLists", categoryLists);
			
			List<Activity> activityList = activityService.findByStatusAndMerchantId(StatusEnum.NORMAL.getValue(), merchant.getId());
			model.addAttribute("activityList", activityList);
			}
			return "commodity/goods/create";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 加载子节点
	 */
	@RequestMapping(value="/ajaxChild",method = RequestMethod.POST)
	@ResponseBody
	public List<Category> ajaxChild(@RequestParam Long pid){
		try{
			List<Category> categoryList = categoryService.getByPcategoryIdAndStatus(pid, StatusEnum.NORMAL.getValue());
			return categoryList;
		}catch(Exception e){
			logger.error("修改排序错误", e);
			return null;
			}
		}


	
	/**
	 * 创建
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(Model model, Goods goods,
			RedirectAttributes redirectAttributes,HttpServletRequest request) {
		try {
			String[] picurls = request.getParameterValues("picList");
			if(picurls!=null){
				for (String str : picurls) {
					GoodsPic pic = new GoodsPic();
					pic.setPicurl(str);
					goods.getGoodsPicList().add(pic);
				}
			}
			goodsService.saveGoods(goods);
			redirectAttributes.addFlashAttribute("message",RedirectMessage.setShowTipSuccess("创建成功"));
			return "redirect:/manage/commodity/goods/list";
		} catch (Exception e) {
			logger.error("创建错误", e);
			return "system/500";
		}
	}

	/**
	 * 编辑页面
	 */
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String setUpdateForm(Model model, @PathVariable("id") Long id) {
		try {
			//商品 , 商户，市场
			Goods goods = goodsService.get(id);
			Merchant merchant = goods.getMerchant();
			Market market = merchant.getMarket();
			model.addAttribute("goods", goods);
			model.addAttribute("market",market);	
			model.addAttribute("merchant", merchant);
			if(market.getId()==MarketEnum.LIFE.getValue()){
				// 父节点分类
				List<Category> categoryLists = categoryService.getCategoryByCorpIdAndMarketIdAndStatusAndParentIdIsNull(1L, market.getId(), StatusEnum.NORMAL.getValue());
				model.addAttribute("categoryLists", categoryLists);
				//子节点分类
				Long pid = goods.getCategory().getPcategory().getId();
				List<Category> categoryList = categoryService.getByPcategoryIdAndStatus(pid, StatusEnum.NORMAL.getValue());
				model.addAttribute("categoryList", categoryList);
			}else{
				// 父节点分类
				List<Category> categoryList = categoryService.getCategoryByCorpIdAndMarketIdAndStatusAndParentIdIsNull(1L, market.getId(), StatusEnum.NORMAL.getValue());
				model.addAttribute("categoryList", categoryList);
			}
			
			//查询活动
			List<Activity> activityList = activityService.findByStatusAndMerchantId(StatusEnum.NORMAL.getValue(), merchant.getId());
			model.addAttribute("activityList", activityList);
			
			return "commodity/goods/update";
		} catch (Exception e) {
			logger.error("编辑页面错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 修改信息
	 */
	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	public String update(@PathVariable("id") Long id,
			@ModelAttribute("goods") Goods goods,GoodsVirtual goodsVirtual,
			RedirectAttributes redirectAttributes,HttpServletRequest request) {
		try {
			
			goodsService.clear();

			String[] picurls = request.getParameterValues("picList");
			if(picurls!=null){
				for (String str : picurls) {
					GoodsPic pic = new GoodsPic();
					pic.setPicurl(str);
					goods.getGoodsPicList().add(pic);
				}
			}
			goodsService.updateGoods(goods);

			redirectAttributes.addFlashAttribute("message",RedirectMessage.setShowTipSuccess("编辑成功"));
			return "redirect:/manage/commodity/goods/list";
		} catch (Exception e) {
			logger.error("编辑错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 删除（逻辑删除）
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String delete(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		try {
			goodsService.deleteLogical(id);
			redirectAttributes.addFlashAttribute("message",
					RedirectMessage.setShowTipSuccess("删除成功"));
			return "redirect:/manage/commodity/goods/list";
		} catch (Exception e) {
			logger.error("删除错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 下架
	 */
	@RequestMapping(value = "/down/{id}", method = RequestMethod.GET)
	public String disable(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		try {
			goodsService.updateStatus(id, GoodsStatusEnum.DOWN.getValue());
			redirectAttributes.addFlashAttribute("message",
					RedirectMessage.setShowTipSuccess("下架成功"));
			return "redirect:/manage/commodity/goods/list";
		} catch (Exception e) {
			logger.error("下架错误,id=" + id, e);
			return "system/500";
		}
	}

	/**
	 * 上架
	 */
	@RequestMapping(value = "/up/{id}", method = RequestMethod.GET)
	public String enable(@PathVariable Long id,
			RedirectAttributes redirectAttributes) {
		try {
		
			goodsService.updateStatus(id, GoodsStatusEnum.UP.getValue());
			redirectAttributes.addFlashAttribute("message",
					RedirectMessage.setShowTipSuccess("上架成功"));
			return "redirect:/manage/commodity/goods/list";
		} catch (Exception e) {
			logger.error("上架错误,id=" + id, e);
			return "system/500";
		}
	}
	
	
	/**
	 * 导入页面
	 */
	@RequestMapping(value="/import",method = RequestMethod.GET)
	public String importForm(Model model){
		try {
			//查询商户  根据商户账号  
			User user = ShiroUser.getInstance().getUser();
			Merchant merchant = merchantService.getMerchantByUserId(user.getId());
									
			//通过市场判断商品是否为虚拟商品
			Market market = merchant.getMarket();
			model.addAttribute("market",market);
			 
			// 查询商品分类和活动
			List<Category> categoryLists = categoryService.findByCorpIdAndMarketIdAndStatus(1L, merchant.getMarket().getId(), StatusEnum.NORMAL.getValue());
			model.addAttribute("categoryLists", categoryLists);
						
			return "commodity/goods/import";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 导入商品
	 */
	@Log(method="导入商品")
	@RequestMapping(value="/import",method = RequestMethod.POST)
	public String importMerchant(DefaultMultipartHttpServletRequest request, 
			Model model, Long categoryid,
			RedirectAttributes redirectAttributes){
		try {
			MultipartFile file = request.getFile("file");
			boolean flag = goodsService.importFile(file, categoryid);
			if(flag){
				redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("导入成功"));
			}else{
				redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("导入失败"));
			}
			return "redirect:/manage/commodity/goods/list";
		} catch (Exception e) {
			logger.error("创建错误", e);
			return "system/500";
		}
	}
	
	
	
	/**
	 * 批量上架
	 * 2015-09-28 by chan
	 * ----------- 参数说明 ----------
	 * ids 商品ID
	 */
	@RequestMapping(value="/batchUp",method = RequestMethod.GET)
	public String batchDelete(@RequestParam String ids,RedirectAttributes redirectAttributes){
		try{
			String id[] = ids.split(",");
			for (String gid : id) {
				Long goodsid = Long.parseLong(gid);
				Goods goods = goodsService.get(goodsid);
				goods.setStatus(GoodsStatusEnum.UP.getValue());
				goodsService.save(goods);
			}
			return "redirect:/manage/commodity/goods/list";
		}catch(Exception e){
			logger.error("批量上架错误,ids="+ids,e);
			return "system/500"; 
		}
	}
	
	/**
	 * 批量下架
	 * 2015-09-28 by chan
	 * ----------- 参数说明 ----------
	 * ids 商品ID
	 */
	@RequestMapping(value="/batchDown",method = RequestMethod.GET)
	public String batchDown(@RequestParam String ids,RedirectAttributes redirectAttributes){
		try{
			String id[] = ids.split(",");
			for (String gid : id) {
				Long goodsid = Long.parseLong(gid);
				Goods goods = goodsService.get(goodsid);
				goods.setStatus(GoodsStatusEnum.DOWN.getValue());
				goodsService.save(goods);
			}
			return "redirect:/manage/commodity/goods/list";
		}catch(Exception e){
			logger.error("批量上架错误,ids="+ids,e);
			return "system/500"; 
		}
	}
}